//
//  FruitBox.swift
//  MixFruit
//
//  Created by remy on 2021/8/23.
//

final class FruitBox {
    enum FruitType: Int, CaseIterable {
        case grape = 1, cherry, orange, lemon, kiwi, tomato, peach, pineapple, cocount, halfwatermelon, watermelon
        var name: String { "fruit/\(self.rawValue)" }
        var bitmask: UInt32 {
            // (6*5)/(2*1),支持15种掩码,满足水果碰撞要求
            switch self {
            case .grape: return 0b000011
            case .cherry: return 0b000101
            case .orange: return 0b000110
            case .lemon: return 0b001001
            case .kiwi: return 0b001010
            case .tomato: return 0b001100
            case .peach: return 0b010001
            case .pineapple: return 0b010010
            case .cocount: return 0b010100
            case .halfwatermelon: return 0b011000
            case .watermelon: return 0b100001
            }
        }
        var score: Int { self.rawValue }
    }
    private let randomList: [FruitType] = [.grape, .cherry, .orange, .lemon, .kiwi]
    var randomIndex: Int = 0
    
    func randomFruit() -> SKSpriteNode {
        var fruit: FruitType
        switch randomIndex {
        case 0...2:
            fruit = .grape
        case 3:
            fruit = .cherry
        case 4:
            fruit = .orange
        default:
            fruit = randomList.randomElement()!
        }
        randomIndex += 1
        let node = makeFruit(fruit)
        node.position = CGPoint(x: UIScreen.width / 2.0, y: UIScreen.height - 50.0)
        return node
    }
    
    func makeFruit(_ type: FruitType) -> SKSpriteNode {
        let node = SKSpriteNode(imageNamed: type.name)
        node.userData = ["type": type, "sound": true]
        return node
    }
    
    func physicsFruit(_ node: SKSpriteNode) {
        guard let type = node.userData?["type"] as? FruitType else { return }
        let pb = SKPhysicsBody(circleOfRadius: node.size.height / 2.0)
        pb.categoryBitMask = type.bitmask
        if type == .watermelon {
            // 西瓜&西瓜不测试碰撞
            pb.contactTestBitMask = ~pb.categoryBitMask
        } else {
            // 其他相同水果测试碰撞
            pb.contactTestBitMask = pb.categoryBitMask
            // 西瓜&西瓜碰撞,其他相同水果不碰撞
            pb.collisionBitMask = ~pb.categoryBitMask
        }
        node.physicsBody = pb
    }
}
